package org.madgecko.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * Author       : MadFrog
 * Date         : 2018/12/13 18:12
 * Description  : Base64解码工具集合
 */
public class Base64Tools {

    /**
     * 将Base64位编码的图片进行解码，并保存到指定目录
     * @param data              Base64数据
     * @param dirPath           文件所在的目录
     * @param fileName          文件名称
     * @throws IOException
     */
    public static void decodeToFile(String data, String dirPath, String fileName) {

        try {
            // 将data开头的非base64字符删除
            String base64 = data.substring(data.indexOf(",") + 1);
            File file = new File(dirPath);
            if(!file.exists()) {
                file.mkdirs();
            }
            String physicalPath = dirPath + "/" + fileName;
            File newFile =new File(physicalPath);
            FileOutputStream write = new FileOutputStream(newFile);
            byte[] decoderBytes = Base64.getDecoder().decode(base64);
            write.write(decoderBytes);
            write.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
